<template>
  <div class="biz-container">
    <table-layout
      :haveSider="false"
      :isSearch="true"
    >
      <template #headCustom>

      </template>
      <template #searchBox>
        <search-layout
          :formInfos="q_formInfos"
          :formDatas="q_formDatas"
          message=""
          @onFind="onFind"
          @onChangeType="onChangeType"
        ></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn
          :addData="false"
          @onAddData="onAddData"
          :delectData="false"
          @onDelectData="onDelectData"
          :optData="optText"
          @onOptData="onBatchAudit"
        >
          <template #cusBtn>
            <a-button
              type="primary"
              @click="onBatchMatch"
            >批量匹配注册证号</a-button>
            <a-button
              style="marginLeft:14px"
              type="primary"
            >智能匹配已绑证照</a-button>
            <a-button
              style="marginLeft:14px"
              type="primary"
              @click="onBatchAudit"
            >批量推送</a-button>
            <a-button
              style="marginLeft:14px"
              type="primary"
              @click="onAllAudit"
            >全部推送</a-button>
          </template>
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <a-list-table
          :columns="columns"
          :tableData="listdata"
          :pagination="pagination"
          :tagClicks2="tagClicks"
          :renderStateByField="renderStateByField"
          :isSelecttion="true"
          :loading="loading"
          :scroll="{y:slotData.tableHeight}"
          @onTableChange="handleTableChange"
          @onselectChange="onselectChange"
          @onAction="onAction"
          :links="links"
          @onTouchlinkCell="onTouchlinkCell"
          @onTouchTagCell="onTouchTagCell"
        >
        </a-list-table>
      </template>
    </table-layout>
    <matchRegModal
      ref="matchRegModal"
      @ok="handleModalSaveOk"
      @close="handleModalCancel"
    />
    <customerSaleGoodsModal
      ref="modal"
      @ok="handleModalSaveOk"
      @close="handleModalCancel"
    />
    <add-seller-lic-modal
      ref="addSellerLicModal"
      @onSaveModal="onSaveModal"
    />
    <add-auth-lic-modal
      ref="addAuthLicModal"
      @onSaveModal="onSaveModal"
    />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import customerSaleGoodsModal from '../customerSalesGoods/customerSaleGoodsModal'
import matchRegModal from './matchRegModal'
import exportExcel from '@/views/app/biz/common/exportExcel/index.vue'
import addSellerLicModal from './addSellerLicModal'
import addAuthLicModal from './addAuthLicModal'
import storage from 'store'
import {
  getByAreaUse,
  getByAreaUseCount,
  pushInfo2
} from '../purchasedGoods/purchasedgoods'

// 字段列表
const columns = [
  //   { title: '数据有效区域(国、省、市、县、院)', dataIndex: 'areaUse', key: 'areaUse', align: 'center' },
  // { title: '商品自编码', dataIndex: 'code', key: 'code', align: 'center' },
  { title: '标准编码', dataIndex: 'standardCode', key: 'standardCode', align: 'center' },
  { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center' },
  //   { title: '英文名称', dataIndex: 'productNameEn', key: 'productNameEn', align: 'center' },
  { title: '通用名', dataIndex: 'commonName', key: 'commonName', align: 'center' },
  // { title: '一级分类', dataIndex: 'first', key: 'first', align: 'center' },
  // { title: '二级分类', dataIndex: 'second', key: 'second', align: 'center' },
  // { title: '三级分类', dataIndex: 'third', key: 'third', align: 'center' },
  //   { title: '规格（特征、参数）', dataIndex: 'spec', key: 'spec', align: 'center' },
  //   { title: '型号(剂型)', dataIndex: 'model', key: 'model', align: 'center' },
  //   { title: '医保代码', dataIndex: 'medicareCode',key: 'medicareCode',   align:'center', },
  //   { title: '描述', dataIndex: 'disc', key: 'disc', align: 'center' },
  { title: '品牌', dataIndex: 'brand', key: 'brand', align: 'center' },
  //   { title: '上市许可持有企业社会编码', dataIndex: 'mahCode', key: 'mahCode', align: 'center' },
  //   { title: '上市许可持有企业中文名', dataIndex: 'mahZh', key: 'mahZh',align:'center'  },
  //   { title: '上市许可持有企业英文名', dataIndex: 'mahEn', key: 'mahEn', align: 'center' },
  //   { title: '生产企业社会编码', dataIndex: 'manufacturerCode', key: 'manufacturerCode', align: 'center' },
  { title: '生产企业名称', dataIndex: 'manufacturerZh', key: 'manufacturerZh', align: 'center', scopedSlots: { customRender: 'manufacturerLicense' } },
  //   { title: '生产企业英文名称', dataIndex: 'manufacturerEn', key: 'manufacturerEn', align: 'center' },
  { title: '产地', dataIndex: 'origin', key: 'origin', align: 'center' },
  { title: '产品类别', dataIndex: 'category', key: 'category', align: 'center' },
  //   { title: '计量单位', dataIndex: 'measurement', key: 'measurement', align: 'center' },
  //   { title: '药品本位码', dataIndex: 'sdc', key: 'sdc', align: 'center' },
  //   { title: '当前批准类型(字典medicalApprovalType)', dataIndex: 'approvalType', key: 'approvalType', align: 'center' },
  { title: '注册证号', dataIndex: 'approvalNum', key: 'approvalNum', align: 'center', scopedSlots: { customRender: 'approvalNum' } },
  // { title: '厂家证照', dataIndex: 'manufacturerLicense',width: 65, key: 'manufacturerLicense', align: 'center',scopedSlots: { customRender: 'manufacturerLicense' } },
  // { title: '授权书', dataIndex: 'letterAuthorization', width: 65,key: 'letterAuthorization', align: 'center',scopedSlots: { customRender: 'letterAuthorization' } },
  //   { title: '当前有效期始', dataIndex: 'approvalDate', key: 'approvalDate', align: 'center' },
  // { title: '有效期', dataIndex: 'validDate', key: 'validDate', align: 'center' },
  { title: '价格（元）', dataIndex: 'price', key: 'price', align: 'center' },
  { title: '状态', dataIndex: 'state', key: 'state', align: 'center', scopedSlots: { customRender: 'saleGoodsState' } },
  // { title: '结算方式', dataIndex: 'settlement', key: 'settlement', align: 'center' },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'operation',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'action' },
  },
]
const renderStateByField = ['saleGoodsState']
const cellTagClicks = ['manufacturerLicense', 'letterAuthorization']
const links = ['areaDm']

export default {
  name: '',
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    matchRegModal,
    exportExcel,
    addSellerLicModal,
    addAuthLicModal,
    customerSaleGoodsModal
  },
  data () {
    return {
      columns: columns,
      listdata: [],
      links: links,
      tagClicks: cellTagClicks,
      renderStateByField: renderStateByField,
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
      },
      // 查询表单
      q_formInfos: [
        { label: '品名', name: 'productNameZh', type: 'input', placeholder: '品名' },
        { label: '生产企业', name: 'manufacturerZh', type: 'input', placeholder: '生产企业' },
        { label: '注册证号', name: 'approvalNum', type: 'zchselect', zhuangTai: '全部', placeholder: '注册证号' },
        { label: '状态', name: 'state', type: 'dicselect', dicName: 'saleGoodsState', placeholder: '状态' },
        { label: ['查询', '重置'], type: 'botton' },
      ],
      // 查询表单绑定数据
      q_formDatas: {
        productNameZh: null,
        manufacturerZh: null,
        approvalNum: null,
        state: null,
        areaUse: null
      },
      pData: {}, // 条件查询参数
      isJump: false,
      optText: '',
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false,
      side: null,
      customerOrgCode: null,
      supplierOrgCode: null
    }
  },
  computed: {},
  watch: {
    $route: {
      handler: function (val, oldVal) {
        console.log(this.$route.name);
        console.log(this.$route.meta);
        //判断是进入该页面还是离开
        if (this.$route.name == 'saleGoodsMatch') {
          //读取该页面是否缓存，未缓存时：
          if (!this.$route.meta.keepAlive) {
            //读取页面跳转传参
            if (this.$route.params.areaDm) {
              this.q_formDatas.areaUse = this.$route.params.areaDm
              storage.set('areaUse', this.$route.params.areaDm)
            } else {
              this.q_formDatas.areaUse = storage.get('areaUse')
            }
            this.getTotal()
            this.getList(this.q_formDatas)
          } else {
            console.log(this.$route.params.isBack);
            //已缓存时判断是否是返回
            if (!this.$route.params.isBack) {
              this.getTotal()
              this.getList(this.q_formDatas)
            }
            this.isJump = false
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  beforeRouteEnter (to, from, next) {
    console.log('beforeRouteEnter', to, from);
    next(vm => {
      console.log(vm.isJump);
    });
  },
  beforeRouteLeave (to, from, next) {
    if (this.isJump) {
      from.meta.keepAlive = true
    } else {
      from.meta.keepAlive = false
    }
    next();
  },
  mounted () {
    console.log('mounted');
    // this.getTotal()
    // this.getList(this.q_formDatas)

  },
  methods: {
    formatParms () {
      let sbdata = JSON.parse(JSON.stringify(this.q_formDatas))
      for (let key in sbdata) {
        console.log(key, sbdata[key]);
        if (!sbdata[key]) {
          sbdata[key] = null
        }
        if (key == 'productNameZh' || key == 'manufacturerZh') {
          if (sbdata[key] == null) {
            sbdata[key] = `%%`
          } else {
            sbdata[key] = `%${sbdata[key]}%`
          }

        }
      }
      return sbdata
    },
    // 初始化页面时得到总数
    async getTotal () {
      let pages = ''
      pages = await getByAreaUseCount(this.formatParms())
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal = (showTotal) => { return `共 ${showTotal} 条` }
      }
    },
    // 初始化查询时的数据列表
    async getList (params) {
      console.log('请求列表时传入的数据', this.formatParms())
      let actionBtn = []
      this.loading = true
      let listdata = []
      let res = ''
      res = await getByAreaUse(this.formatParms(), this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        for (let item of resdata) {
          this.customerOrgCode = item.customerOrgCode
          this.supplierOrgCode = item.supplierOrgCode
          if (item.state == this.appState.saleGoodsState.unPush.code) {
            actionBtn = ['推送', '编辑',]
          } else {
            actionBtn = ['查看']
          }
          listdata.push({
            key: item.pid,
            standardCode: item.code,
            action: actionBtn,
            ...item
          }
          )
        }
        this.listdata = listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 新增按钮 点击了新增
    onAddData () {

    },
    // 关闭模态详细框
    handleModalCancel () {
    },
    // 模态详细框提交按钮
    handleModalSaveOk () {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction (text, record, index) {
      if (text == '编辑') {
        //编辑
        this.$refs.modal.editModal(record.pid)
      } else if (text == '推送') {
        this.showConfirm(record, '1')
      }
    },
    showConfirm (val, type) {
      let datas = {
        state: "待审核",
        customerOrgCode: this.customerOrgCode,
        supplierOrgCode: this.supplierOrgCode
      }
      if (type == '1') {
        datas.pids = val.pid
      }
      if (type == "all") {
        datas.pids = "all"
      }
      if (type == "batch") {
        datas.pids = ''
        for (const item of val) {
          datas.pids += item.pid + ','
        }
      }
      const that = this;
      this.$confirm({
        title: '是否确认推送？',
        content: '请确认推送的商品已关联证照信息和生产厂家信息',
        onOk () {
          that.submitPush(datas)
        },
        onCancel () { },
      });
    },
    async submitPush (val) {
      console.log(val);
      let res = await pushInfo2(val)
      console.log(res);
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '推送成功', duration: 3 })
      } else {
        this.$message.error({ content: '推送失败，原因：' + res.message, duration: 3 })
      }
      this.handleModalSaveOk()
    },
    onBatchMatch () {
      this.$refs.matchRegModal.matchAllModal()
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 搜索栏选择下拉select触发搜索val[0]表示选中的record中的pid,val[1]表示选中的record全部信息
    onChangeType (name, val) {
      console.log('formName', name)
      console.log('val', val)
      switch (name) {
        case 'pid':
          if (!val[0]) {
            this.q_formDatas.pid = null
          }
          this.onFind()
          break
        case 'approvalNum':
          if (!val) {
            this.q_formDatas.approvalNum = null
          }
          this.onFind()
          break
        case 'state':
          if (!val) {
            this.q_formDatas.state = null
          }
          this.onFind()
          break
      }
    },
    // 查询按钮
    onFind () {
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },

    onTouchlinkCell (text, record, index, link) {
      console.log(record);
      if (link == 'areaDm') {
        // this.$refs.matchRegModal.editModal(record.pid)
      }
    },
    onTouchTagCell (text, record, index, col) {
      if (col == 'manufacturerLicense') {
        console.log('点击了商家证照的tag:', col);
        if (record.manufacturerPid) {
          //点击了商家证照查看的tag
          this.$refs.addSellerLicModal.editModal(record.pid, true, record)
        } else {
          //点击了商家证照上传的tag
          this.$refs.addSellerLicModal.addModal(record.pid, record)
        }
      } else if (col == 'letterAuthorization') {
        console.log('点击了授权书的tag:', col);
        if (text == '0') {
          //点击了授权书上传的tag
          this.$refs.addAuthLicModal.addModal(record.pid, record)
        } else {
          //点击了授权书查看的tag
          this.$refs.addAuthLicModal.editModal(record.pid, true, record)
        }
      } else if (col == 'approvalNum') {
        this.$refs.matchRegModal.matchAllModal(record.pid)
      }
    },
    onSaveModal () {
      this.getList(this.q_formDatas)
    },
    // 多选批量操作
    onselectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.state == this.appState.saleGoodsState.pushed.code) {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onDelectData () {
      if (this.selectedRows.length) {
        this.showDelConfirm(this.selectedRows)
      } else {
        this.$message.warning({ content: '未选择要删除的记录', duration: 3 })
      }
    },
    showDelConfirm (val, type) {
      let datas = []
      if (type == '1') {
        datas[0] = val
      } else {
        datas = val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk () {
          let reqArr = []
          let key = 'self'
          for (const item of datas) {
            reqArr.push(that.delOrder(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content: '记录删除成功', duration: 3 })
              } else {
                that.$message.error({ content: '记录删除失败，原因：' + item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content: '操作出错:' + err, duration: 3 })
          })
        },
        onCancel () { },
      });
    },
    async delOrder (val) {
      let res = await deleteInfo(val)
      return res
    },
    onBatchAudit () {
      if (this.selectedRows.length) {
        this.showConfirm(this.selectedRows, 'batch')
      } else {
        this.$message.warning({ content: '未选择要审核的记录', duration: 3 })
      }
    },
    onAllAudit () {
      this.showConfirm([], 'all')
    }
  },
}
</script>

<style>
.importTip {
  line-height: 40px;
  font-size: 14px;
  color: #fab600;
}
</style>